package com.lbssoft.gpsbd.config.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lbssoft.gpsbd.common.ErrorEnum;
import com.lbssoft.gpsbd.model.Result;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

public class MyFilter extends AccessControlFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String authorization = httpServletRequest.getHeader("token");
        System.out.println("token验证"+authorization);
        if (authorization!=null) {
            try {
            	MyToken token = new MyToken(authorization);
                // 提交给realm进行登入，如果错误他会抛出异常并被捕获
                getSubject(request, response).login(token);
                return true;
            } catch (Exception e) {
                response401(request, response);
                return false;
            }
        } else {
            response401(request, response);
            return false;
        }
    }

    /**
     * 将请求返回到 /401
     */
    private void response401(ServletRequest req, ServletResponse resp) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
        PrintWriter out = null;
        JSONObject jsonObject = new JSONObject();
        Result result = new Result();
        result.setMsg(ErrorEnum.E_401.getErrorMsg());
        result.setCode(ErrorEnum.E_401.getErrorCode());

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        out = resp.getWriter();
        out.println(JSON.toJSON(result));
    }
}
